package com.cjst.config;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisServer;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.cjst.pojo.base.AlarmResult;
import com.cjst.pojo.sys.SysUser;
import com.cjst.service.base.AlarmResultService;
import com.cjst.service.dubbo.BroadCastDubboService;
import com.cjst.service.dubbo.HkDubboService;
import com.cjst.service.part.PartConnectionParametersService;
import com.cjst.service.redis.RedisService;
import com.cjst.service.sys.SysUserService;
import com.cjst.util.FileToByte;
import com.cjst.util.MyMap;
import com.cjst.util.SendSmsUtil;
import com.cjst.util.common.DateUtil;
import com.itextpdf.text.log.SysoCounter;

@Component
public class Scheduler {
	private static final Logger log = Logger.getLogger(Scheduler.class);
	@Value("${img.location}")
	private String uploadDir;
	@Reference
	private HkDubboService hkDubboService;
	@Autowired
	private SendSmsUtil sendSmsUtil;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private RedisService redisService;
	@Autowired
	private AlarmResultService alarmResultService;			//报警记录
	@Autowired
	private PartConnectionParametersService parametersService;			//智能设备参数 
	@Reference
	private BroadCastDubboService broadCastDubboService;
	
	private final static ReentrantLock lock=new ReentrantLock();
	//每隔5秒执行一次
    //@Scheduled(fixedRate = 3000)
    public void hkAnalyse() {
    	log.info("Scheduler");
    	//String result=hkDubboService.analyse("192.168.0.88", 8000, "admin", "chengjist123456");
    	//JSONObject jsonObject = JSONObject.parseObject(result);
    	//Integer resultCode=jsonObject.getInteger("resultCode");
    	Map<String, Object> map=hkDubboService.analyseByMap("192.168.0.88", 8000, "admin", "chengjist123456");
    	if(map!=null){
			//Float score=(Float) map.get("score");
			String type=(String) map.get("type");
			int code=(int) map.get("code");
			List<SysUser> sysList=sysUserService.list(null);				//后面根据实际设备得到值
			Map<String, Object> templateParamMap=new HashMap<String, Object>();
			templateParamMap.put("code", 1);
			AlarmResult ar=new AlarmResult();
			ar.setType(1);   				//自动触发
			ar.setPartId("1");
			String content="";
			if(code==1){				//设备异常
				Object obj=redisService.getObj("sbsss"+1);
				if(obj==null || obj.equals(null)){
					content="设备故障或关机";
					templateParamMap.put("content", content);
					ar.setAlarmExplain("1号设备设备故障或关机");
					if(sysList!=null && sysList.size()>0){ 
						for (SysUser sysUser : sysList) { 
							sendSmsUtil.sendSms(sysUser.getPhone(), "SMS_177360063", templateParamMap, "", null, "植城智慧", "设备故障");
						}
						ar.setAlarmType("设备故障");
						MyMap.getMyMap().put2("broadcast_"+1+DateUtil.dateToString(new Date()), "1号摄像头故障，请到现场查看");
						alarmResultService.addLocalByid(ar);
					}
					
					redisService.setObjByTime("sbsss"+1, 1, 24*60*60);
				}
			}else{
				int bz=0;
				int flag=(int) map.get("flag");
				log.info("=========type"+type);
					
				if(flag==0){					//不文明行为
					templateParamMap.put("content", "有疑似"+type+"人");
					ar.setAlarmExplain("1号摄像头下某人，已经发现你了，请不要"+type);
					MyMap.getMyMap().put2("broadcast_"+1+DateUtil.dateToString(new Date()), "请不要"+type);
					bz=1;
				}else if(flag==1){			//动物
					templateParamMap.put("content", "有疑似携带"+type+"的人");
					ar.setAlarmExplain("1号摄像头下某人，已经发现你了，请不要携带宠物"+type+"入园");
					MyMap.getMyMap().put2("broadcast_"+1+DateUtil.dateToString(new Date()), "请不要携带宠物"+type+"入园");
					bz=1;
				}
				if(sysList!=null && sysList.size()>0){
					for (SysUser sysUser : sysList) {
						sendSmsUtil.sendSms(sysUser.getPhone(), "SMS_177360063", templateParamMap, "", null, "植城智慧", "视频报警");
					}
				}
				if(bz==1){
					byte[] img64=(byte[]) map.get("img");
					//byte[] img64=strImg64.getBytes();
					String imgUrl="/alarm/"+"1/"+DateUtil.dateToString(new Date(),"yyyyMMddHHmmss")+".jpg";
					FileToByte.byte2image(img64, uploadDir+imgUrl);
					ar.setImgUrl(imgUrl);
					ar.setIsBroadcast(1);
					ar.setAlarmType("视频报警");
					ar.setFback("1");
					//ar.setCreateTime(DateUtil.stringToDate(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss"));
					alarmResultService.addLocalByid(ar);
				}
			}
				
    	}else{
			log.info("=========未发现异常");
		}
    }
    @Scheduled(fixedRate = 3000)
    public void branck() {
    	try {
			lock.lock();
			Map<String, String> map=MyMap.getMyMap().getMap2();
			if(!map.isEmpty()){
				for(Map.Entry<String, String> entry : map.entrySet()){
					String mapKey = entry.getKey();
					String mapValue = entry.getValue();
					broadCastDubboService.skPlay(1, 1, mapValue, "1", 1);			//播放
					MyMap.getMyMap().getMap2().remove(mapKey);
				}
			}
    	}catch (Exception e) {
			e.printStackTrace();
		}finally {
			lock.unlock();
		}
    }
    //每天3：05执行
   /* @Scheduled(cron = "0 05 03 ? * *")
    public void testTasks() {
    }*/
  /* public static void main(String[] args) {
		String fileDir="E:/image/baiduMind/image/1.jpg";
		byte[] img64=FileToByte.readFile(fileDir);
		String s = new String(img64);
		//String str = Base64.encodeToString(mBuff,Base64.DEFAULT);
		FileToByte.byte2image(img64, "E:/image/4.jpg");
	}*/
    
    
    /*public static void main(String[] args) {
    	String[] a = { "111111", "cj010", "JPJGCQVVH4JANK9J8834D4463A0640CCBED8B1668A2AAB92" ,"MQ4uP2W9AJPgcQVR28BDE806E74B478DB666D5165DF8F5D9"};
    	
    	
		String url_api="http://192.168.0.159:80/api/location/test";
		String url_web="http://192.168.0.159:8086/tmp/test";
		
		
		Runnable runnable2 = new Runnable() {
			//创建 run 方法
			public void run() {
				try {
					String result=httpPOST(url_api,initData(a));
					System.out.println("=================POST==================");
					System.out.println(result);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		// ScheduledExecutorService:是从Java SE5的java.util.concurrent里，
		// 做为并发工具类被引进的，这是最理想的定时任务实现方式。
		ScheduledExecutorService service = Executors
				.newSingleThreadScheduledExecutor();
		// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
		// 10：秒   5：秒
		// 第一次执行的时间为10秒，然后每隔五秒执行一次
		service.scheduleAtFixedRate(runnable2, 4, 10, TimeUnit.SECONDS);
		
	}
    
    public static String httpPOST(String url,String jsonParams) throws IOException {
		String result = "";
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost  httpPost  = new HttpPost (url);
			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
			//httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
			
			StringEntity postingString = new StringEntity(jsonParams,"utf-8");
			postingString.setContentType("application/x-www-form-urlencoded");
			httpPost.setEntity(postingString);
			
			HttpResponse response = httpclient.execute(httpPost);
			
			InputStream in = response.getEntity().getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
			StringBuilder strber= new StringBuilder();
			String line = null;
			while((line = br.readLine())!=null){
				strber.append(line+'\n');
			}
			br.close();
			in.close();
			result = strber.toString();
		} finally {
			httpclient.close();
		}
		return result;
	}
    
    public static String HttpURLConnectionGET(String requestUrl) {
		// buffer用于接受返回的字符
		StringBuffer buffer = new StringBuffer();
		try {

			URL url = new URL(requestUrl);
			// 打开http连接
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoInput(true);

			
			 * It may update someday; POST,GET,DELETE,ETC
			 
			httpUrlConn.setRequestMethod("GET");

			httpUrlConn.connect();

			// 获得输入
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			// 将bufferReader的值给放到buffer里
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			// 关闭bufferReader和输入流
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			// 断开连接
			httpUrlConn.disconnect();

		} catch (Exception e) {
			e.printStackTrace();
		}
		// 返回字符串
		return buffer.toString();
	}
    
    public static String initData(String[] tmp) {
		
		String result="passWord="+tmp[0]+"&userName="+tmp[1]+"&userId="+tmp[2]+"&token="+tmp[3];
		
		return result;
	}*/
}






